package com.apps.ppt.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.apps.compress.ZipComPressHelper;
import com.apps.file.service.FileHelper;
import com.apps.globals.color.service.IKupaColorService;
import com.apps.globals.global.model.po.KupaGlobalPptNamelib;
import com.apps.globals.global.service.IKupaGlobalFilterWordsService;
import com.apps.globals.global.service.IKupaGlobalPptNamelibService;
import com.apps.goods.model.po.KupaGoods;
import com.apps.goods.service.IKupaGoodsService;
import com.apps.image.ImagesSimilarHelper;
import com.apps.globals.color.model.vo.RGB;
import com.apps.ppt.service.PPtService;
import com.apps.ppt.service.model.vo.PPtInfoVo;
import com.apps.ppt.service.PPtUpLoadService;
import com.apps.ppt.utils.PPtxContextHelper;
import com.apps.thirdparty.upload.alioss.service.IKupaOssUploadService;
import com.hankcs.hanlp.dictionary.CoreSynonymDictionary;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.List;

@Slf4j
@Service
public class PPtUpLoadServiceImpl implements PPtUpLoadService {

    @Autowired
    private IKupaGoodsService goodsService;

    @Autowired
    private PPtService pPtService;

    @Autowired
    private IKupaGlobalFilterWordsService filterWordsService;

    @Autowired
    private IKupaGlobalPptNamelibService pptNamelibService;

    @Autowired
    private IKupaColorService colorService;

    @Autowired
    private IKupaOssUploadService ossUploadService;

    @SneakyThrows
    @Override
    public void upload(String path) {
        //扫描出所有pptx文件
        List<String> ppts= FileHelper.scanFilesWithNoRecursion(path,true,"pptx","ppt");
        log.info("共计扫描到"+ppts.size()+"个ppt文件");
        log.info("开始进行预处理");
        //遍历并且对每个文件生成单独文件夹备用
        for(int i=0;i<ppts.size();i++)
        {
            String file = ppts.get(i);
            //ppt数据
            PPtInfoVo infoVo=null;
            //打开文件
            File input=new File(file);
            //获取ppt的名字,默认都是上级文件夹的名字
            String pptName = new File(input.getParent()).getName();
            //信息文件
            File info=new File(input.getAbsolutePath().split("\\.")[0]+".txt");
            if(info.exists())
                continue;
            //新建文件目录,必须信息文件和文件夹不存在才能新建
            File newFlod=new File(file.split("\\.")[0]);
            if(!newFlod.exists()) {
                //创建文件夹
                newFlod.mkdirs();
                file = newFlod.getAbsolutePath()+"/"+input.getName();
                //移动文件到新文件夹
                Files.move(Paths.get(input.getAbsolutePath()),Paths.get(file), StandardCopyOption.REPLACE_EXISTING);
                //生成信息文件
                info = new File(newFlod.getAbsolutePath()+"/"+input.getName().split("\\.")[0]+".txt");
                info.createNewFile();
                //重新加载下文件
                input = new File(file);
            }

            try {
                 //读取ppt 并生成缩略图和详情图
                infoVo = pPtService.readPPt(input,"thumb","detail");
                //生成压缩包
                infoVo.setZipPath(ZipComPressHelper.writeZip(file));
                //设置ppt内容
                infoVo.setContext(PPtxContextHelper.readDoc(input));
                //设置ppt名字
                infoVo.setPptName(pptName);
            }catch (Exception e)
            {
                e.printStackTrace();
//                log.info(file+"读取异常 删除");
//                File delete=new File(input.getParent());
//                //删除异常文件
//                FileUtils.deleteDirectory(delete);
                continue;
            }
            //提取ppt的主色调,白色和灰色排除
            String mainColor= colorService.recognition(infoVo.getThumbBuffer(),new RGB(255,255,255),new RGB(204,204,204));
            //oss存储文件夹
            String ossMainFlod="ppt";
            String ossSaveFold=infoVo.getPptName()+"/"+input.getName().split("\\.")[0];
            KupaGoods goods=new KupaGoods();
            goods.setGoods_name(infoVo.getPptName()+mainColor);
//            goods.setGoods_download(ossUploadService.upload(infoVo.getZipPath(),ossMainFlod,ossSaveFold));
//            goods.setGoods_thumbnail(ossUploadService.upload(infoVo.getThumbPath(),ossMainFlod,ossSaveFold));
//            goods.setGoods_context(ossUploadService.upload(infoVo.getDetailPath(),ossMainFlod,ossSaveFold));
            log.info(goods.toString());

            float progress = (((float)(i+1)*((float)ppts.size()/100.0f))/(float)ppts.size())*100.0f;
            log.info("上传完成进度:"+progress+"%");
        }
        log.info("预处理完毕");
    }

//    @RunTimes
    @SneakyThrows
    @Override
    public void addWorldLib(String path)
    {
        log.info("开始添加词库");
        List<String> pyresult=FileHelper.readTxtFile(path);
        for(int i=0;i<pyresult.size();i++)
        {
            try {
                JSONObject jsonObject=JSON.parseObject(pyresult.get(i));
                String phash= ImagesSimilarHelper.getPhash(ImageIO.read(new URL(jsonObject.getString("src"))));
                KupaGlobalPptNamelib pptNamelib=new KupaGlobalPptNamelib();
                pptNamelib.setName(jsonObject.getString("name"));
                pptNamelib.setUrl(jsonObject.getString("src"));
                pptNamelib.setPhash(phash);
                pptNamelibService.saveToDB(pptNamelib);
            }catch (Exception e)
            {
                e.printStackTrace();
                continue;
            }
        }
        log.info("添加完毕");
    }

    /**
     * 在图库中查找有没有一样的图片
     * @param phash
     * @return
     */
    private KupaGlobalPptNamelib isSimilar(String phash)
    {
        List<KupaGlobalPptNamelib> pptNamelibs=pptNamelibService.getLibs();
        for(KupaGlobalPptNamelib item:pptNamelibs)
        {
            int distance=ImagesSimilarHelper.distance(phash,item.getPhash());
            if(distance < 1) {
                return item;
            }
        }
        return null;
    }

    @SneakyThrows
    private KupaGlobalPptNamelib findLower(BufferedImage image)
    {
         String phash=ImagesSimilarHelper.getPhash(image);
        //找出最接近的图片
        List<KupaGlobalPptNamelib> pptNamelibs=pptNamelibService.getLibs();
        for(KupaGlobalPptNamelib item:pptNamelibs)
        {
            int now_dis=ImagesSimilarHelper.distance(phash,item.getPhash());
            //如果找到距离小于等于1的就终止查找
            if(now_dis <=6 )
               return item;
        }
        return null;
    }

    @SneakyThrows
    private KupaGlobalPptNamelib findLower(String path)
    {
        String phash=ImagesSimilarHelper.getPhash(ImageIO.read(new File(path)));
        //找出最接近的图片
        List<KupaGlobalPptNamelib> pptNamelibs=pptNamelibService.getLibs();
        KupaGlobalPptNamelib record=pptNamelibs.get(0);
        int dis=100;
        for(KupaGlobalPptNamelib item:pptNamelibs)
        {
            int now_dis=ImagesSimilarHelper.distance(phash,item.getPhash());
            if(now_dis < dis)
            {
                dis=now_dis;
                record = item;
            }
            //如果找到距离小于等于1的就终止查找
            if(dis <=1 )
                break;
        }
        log.info("dis:"+dis);
        return record;
    }

    @SneakyThrows
    @Override
    public void onLoad()
    {
        //upload("I:\\素材\\ppt\\综合系列-1\\");
//        log.info("开始查词");
//          log.info(findLower("I:\\素材\\ppt\\扁平风格-1\\扁平风格(19)\\thumb.jpg").toString());
//        addWorldLib("E:\\python-workspace\\kupa8\\file\\tukuppt.txt");
//        addWorldLib("E:\\python-workspace\\kupa8\\file\\yagsan.txt");
//        addWorldLib("E:\\python-workspace\\kupa8\\file\\pptcn.txt");
//        addWorldLib("E:\\python-workspace\\kupa8\\file\\ooopic.txt");
//        try {
//            String world= PPtxContextHelper.readDoc("I:\\素材\\扁平风格\\扁平风格(3).ppt");
//            log.info(world);
//            //去掉英文
//            world = LanguageHelper.filterEnglish(world);
//
//            List<String> phraseList = HanLP.extractPhrase(world, 5);
//            log.info(""+phraseList);
//            String result="";
//            //去掉过滤词
//            for(String wo:phraseList)
//            {
//                int count=0;
//                for(String filter:filterWordsService.getWorlds())
//                {
//                    if(wo.contains(filter))
//                        count++;
//                }
//                if(count == 0)
//                    result+=wo+",";
//            }
//
////            List<Term> termList = StandardTokenizer.segment(result);
////            log.info(""+termList);
//            List<String> sentenceList = HanLP.extractSummary(result, 5);
//            log.info(""+sentenceList);
//            log.info("result:"+result);
//        }catch (Exception e)
//        {
//            e.printStackTrace();
//        }

    }

    public static void main(String... args)
    {
        String context=PPtxContextHelper.readDoc("I:\\素材\\ppt\\综合系列-1\\精品系列(37).pptx");
       System.out.println(context);
    }
}
